package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.thread.ThreadUtil;
import com.hmdp.common.RedisIdWorker;
import com.hmdp.dto.Result;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.SeckillVoucherMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IVoucherOrderService;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.Duration;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 秒杀优惠券表，与优惠券是一对一关系 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2022-01-04
 */
@Service
@Slf4j
public class SeckillVoucherServiceImpl extends ServiceImpl<SeckillVoucherMapper, SeckillVoucher> implements ISeckillVoucherService {

    @Autowired
    private RedisIdWorker idWorker;

    @Resource
    private SeckillVoucherMapper seckillVoucherMapper;

    @Autowired
    private IVoucherOrderService voucherOrderService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    private ISeckillVoucherService currentProxy;

    private final String queueName = "stream.orders";

    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;

    static {
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }

    @SuppressWarnings("unchecked")
    @PostConstruct
    public void init(){
        ThreadUtil.execute(()->{

            while (true){
                try {
                    //获取消息队列中的订单信息 XREADGROUP GROUP g1 consumer1 COUNT BLOCK 2000 STREAMS stream.orders >
                    List<MapRecord<String, Object, Object>> recordList = redisTemplate.opsForStream().read(
                            Consumer.from("group1", "consumer1"),
                            StreamReadOptions.empty().count(1).block(Duration.ofSeconds(10)),
                            StreamOffset.create(queueName, ReadOffset.lastConsumed())
                    );
                    //判断是否有消息
                    if(CollectionUtil.isEmpty(recordList)){
                        continue;
                    }
                    //解析消息
                    MapRecord<String, Object, Object> mapRecord = recordList.get(0);
                    RecordId messageId = mapRecord.getId();//消息的ID
                    Map<Object, Object> objectMap = mapRecord.getValue();
                    VoucherOrder order = BeanUtil.fillBeanWithMap(objectMap, new VoucherOrder(), true);
                    //处理消息
                    currentProxy.createVoucherOrder(order);
                    //ACK确认 ACK stream.orders group1 id
                    redisTemplate.opsForStream().acknowledge(queueName,"group1",messageId);
                }catch (Exception e){
                    log.error("处理订单异常",e);
                    handlePendingList();
                }
            }
        });
    }

    /**
     *  xgroup create stream.orders group1 0 mkstream 创建消费者组
     */

    @SuppressWarnings("unchecked")
    private void handlePendingList() {
        while (true) {
            try {
                //获取消息队列中的订单信息 XREADGROUP GROUP g1 consumer1 COUNT BLOCK 2000 STREAMS stream.orders 0
                List<MapRecord<String, Object, Object>> recordList = redisTemplate.opsForStream().read(
                        Consumer.from("group1", "consumer1"),
                        StreamReadOptions.empty().count(1).block(Duration.ofSeconds(10)),
                        StreamOffset.create(queueName, ReadOffset.from("0"))
                );
                //判断是否有消息
                if (CollectionUtil.isEmpty(recordList)) {
                    //没有消息应该结束循环
                    break;
                }
                //解析消息
                MapRecord<String, Object, Object> mapRecord = recordList.get(0);
                RecordId messageId = mapRecord.getId();//消息的ID
                Map<Object, Object> objectMap = mapRecord.getValue();
                VoucherOrder order = BeanUtil.fillBeanWithMap(objectMap, new VoucherOrder(), true);
                //处理消息
                currentProxy.createVoucherOrder(order);
                //ACK确认 ACK stream.orders group1 id
                redisTemplate.opsForStream().acknowledge(queueName, "group1", messageId);
            } catch (Exception e) {
                log.error("处理订单异常", e);
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException interruptedException) {
                    log.error("中断异常...");
                }
            }
        }
    }


    @SuppressWarnings("ConstantConditions")
    @Override
    public Result seckillVoucher(Long voucherId){
        currentProxy = (ISeckillVoucherService)AopContext.currentProxy();
        long orderId = idWorker.nextId("order");
        Long userId = UserHolder.getUser().getId();
        //执行lua脚本:判断用户是否具有资格，扣除库存并下单，然后发送消息。
        Long result = redisTemplate.execute(
                SECKILL_SCRIPT,
                Collections.emptyList(),//KEYS[1]
                voucherId.toString(), //AVGS[1]
                String.valueOf(userId),      //AVGS[2]
                String.valueOf(orderId)      //AVGS[3]
        );
        //如果不具有资格
        if(0 != result){
            return Result.fail(result==1?"库存不足":"不可重复下单");
        }
        //返回订单ID
        return Result.ok(orderId);
    }

    @Transactional
    @Override
    public void createVoucherOrder(VoucherOrder order){
        log.info("订单来啦！{}",order.getId());
        Long voucherId = order.getVoucherId();
        Long userId = order.getUserId();
        Integer count = seckillVoucherMapper.countByUserIdAndVoucherId(voucherId, userId);
        if(count>0){
            log.info("不可重复下单");
            return;
        }
        //扣减库存
        boolean success = seckillVoucherMapper.minusStcokOne(voucherId);
        if(!success){
            log.info("库存不足！");
            return;
        }
        voucherOrderService.save(order);
        Result.ok(order.getId());
    }
}
